import base64
import json
import os
import subprocess
import time

import lokalise
import requests

from kimi_client import KimiClient

TOKEN = 'b602ae315e398faac005abc969a8dfff10a826af'
ANDROID_PROJECT_ID = '8483564464a3b46094c650.87849900'
client = lokalise.Client(TOKEN)
project = client.project(ANDROID_PROJECT_ID)


# 列出 lang_id
# for item in client.project_languages(ANDROID_PROJECT_ID).items:
#     print(item.lang_name, item.lang_id)

# Chinese Simplified 602
# Chinese Traditional 601
# English 640
# Spanish 1056

def run_git_command(command):
    result = subprocess.run(
        command.split(),  # 将命令拆分为参数列表
        stdout=subprocess.PIPE,  # 捕获标准输出
        stderr=subprocess.PIPE,  # 捕获标准错误
        text=True  # 将输出解码为文本
    )
    if result.returncode == 0:
        return result.stdout.strip()  # 返回命令输出，去除首尾空白
    else:
        print("Error:", result.stderr)
        return None


def encode_file_to_base64(file_path):
    try:
        with open(file_path, "rb") as file:
            # 读取文件内容
            file_content = file.read()
            # 对文件内容进行 Base64 编码
            encoded_content = base64.b64encode(file_content)
            return encoded_content.decode('utf-8')
    except Exception as e:
        print(f"Base64编码失败：{e}")
        return None


def upload(file, lang):
    base64 = encode_file_to_base64(file)
    process = client.upload_file(ANDROID_PROJECT_ID, {
        "data": base64,
        "filename": os.path.basename(file),
        "lang_iso": lang,
        "replace_modified": True,
        "slashn_to_linebreak": False
    })
    time.sleep(1)
    process = client.queued_process(ANDROID_PROJECT_ID, process.process_id)
    print(process)


def getBotContent():
    url = "http://localhost:11434/api/chat"
    payload = json.dumps({
        "model": "qwen:7b",
        "messages": [
            {
                "role": "system",
                "content": "你是lbq开发的机器人,主要任务是发送通知,根据目标任务撰写通知语,使用二次元语气,直接发送通知内容，50字以内,要委婉好听。"
            },
            {
                "role": "user",
                "content": "我们的android项目有一批语言已更新，需要翻译的小伙伴依照英语以及简体对繁体和西班牙语进行翻译。"
            }
        ],
        "stream": False
    })
    headers = {
        'Content-Type': 'application/json'
    }

    try:
        response = requests.request("POST", url, headers=headers, data=payload)
        return json.loads(response.text)["message"]["content"]
    except Exception as e:
        return None


def postFeishu(str, aiTrans):
    email = run_git_command("git config user.email")
    url = "https://open.feishu.cn/open-apis/bot/v2/hook/b758c0f3-1e62-436c-b4fb-15e7d251e016"
    notiContent = getBotContent()
    if notiContent is not None:
        notiContent = notiContent + "\n" + "需要翻译的Keys如下:"
    else:
        notiContent = "需要翻译的Keys如下:"
    card = json.dumps({
        "elements": [
            {
                "tag": "markdown",
                "content": "**<at email=shangguanling@flowcapai.com></at> ** " + notiContent
            },
            {
                "tag": "hr"
            },
            {
                "tag": "div",
                "text": {
                    "content": str,
                    "tag": "plain_text"
                }
            },
            {
                "tag": "hr"
            },
            {
                "tag": "markdown",
                "content": "**AI翻译仅供参考**\n\n" + aiTrans
            },
            {
                "tag": "div",
                "text": {
                    "tag": "lark_md",
                    "content": "温馨提示: 翻译成西班牙语或其他语言时应尽量简洁，确保长度不超过英语原文。翻译完成后请<at email=" + email + "></at>及时更新Android多语翻译。"
                },
                "extra": {
                    "tag": "button",
                    "text": {
                        "tag": "lark_md",
                        "content": "直达翻译"
                    },
                    "type": "primary",
                    "multi_url": {
                        "url": "https://app.lokalise.com/project/8483564464a3b46094c650.87849900/?view=multi&filter"
                               "=builtin_1",
                        "android_url": "",
                        "ios_url": "",
                        "pc_url": ""
                    }
                }
            },
            {
                "tag": "note",
                "elements": [
                    {
                        "tag": "img",
                        "img_key": "img_v3_029f_e949bff7-601c-4abb-b815-5b7382d5117g",
                        "alt": {
                            "tag": "plain_text",
                            "content": ""
                        }
                    },
                    {
                        "tag": "plain_text",
                        "content": "WorkFlow"
                    }
                ]
            }
        ],
        "header": {
            "template": "blue",
            "title": {
                "content": "【RockFlow-Android】多语需要翻译",
                "tag": "plain_text"
            }
        }
    })
    headers = {
        'Content-Type': 'application/json'
    }
    body = json.dumps({"msg_type": "interactive", "card": card})
    headers = {"Content-Type": "application/json"}
    requests.post(url=url, data=body, headers=headers)


def startAiTranslate(englishTranslations, zhCnTranslations):
    prompt = """【多语翻译】根据英语和中文简体,翻译成中文繁体和西班牙语。
你是一个App多语翻译专家,现在我将给你多个英语和中文简体,请你翻译成中文繁体和西班牙语。
input： 一个json字符串,比如:
    {
        "input": [{
            "zh-cn": "你好",
            "en": "hello",
            "en_length":5
        }]
    }
其中zh-cn表示简体中文,en表示英文,en_length表示英文翻译的长度。
output：以一个json字符串,比如:
{
    "output": [{
        "zh-tw": "你好",
        "es": "Hola",
        "es_length":4
    }]
}
其中zh-tw表示繁体中文,es表示西班牙语,es_length表示西班牙语翻译的长度
##注意
-您翻译的西班牙语(es)的长度要尽可能的短,切记不要超过英语的文档长度(长度计算是python的len方法,es_length<=en_length),否则在App显示可能不全，用户体验很差。
-当我给你input的json时,你才能继续回复output
-你的返回是一个json字符串,不要反悔其他
现在我要给你提供input:
        """
    resultTrnas = []
    for index, item in enumerate(englishTranslations):
        resultTrnas.append(
            {
                "zh-cn": zhCnTranslations[index],
                "en": item,
                "en_length": len(item)
            }
        )

    result = json.dumps({"input": resultTrnas}, indent=4, ensure_ascii=False)
    prompt += "\n" + result + "\n请你给出output。"

    client = KimiClient()
    kimiResult = client.doPrompt(
        prompt, needDocument=False
    )
    print(kimiResult)
    if "```json" in kimiResult:
        kimiResult = kimiResult.split("```json")[1]
        kimiResult = kimiResult.split("```")[0]
    transObj = json.loads(kimiResult)
    return transObj


def checkUnTranslate():
    words = client.keys(ANDROID_PROJECT_ID, {
        "filter_untranslated": 1,
        "page": 1,
        "limit": 1000,
        "filenames": "android",
        "filter_translation_lang_ids": "601,602,640,1056",
        "filter_platforms": "android",
        "include_translations": 1
    })
    needTranslations = []
    englishTranslations = []
    zhCnTranslations = []
    for item in words.items:
        attributes = item.custom_attributes
        if len(attributes) > 0 and json.loads(attributes)["translatable"] == "false":
            continue
        if item.key_name == "empty":
            continue
        for transItem in item.translations:
            if transItem['language_iso'] == "zh_CN":
                zhCnTranslations.append(transItem['translation'])
            if transItem['language_iso'] == "en":
                englishTranslations.append(transItem['translation'])
        keyName = item.key_name["android"]
        needTranslations.append(keyName)
    if len(needTranslations) > 0:
        aiTrans = startAiTranslate(englishTranslations, zhCnTranslations)
        aiResult = ""
        for index, item in enumerate(needTranslations):
            aiResult += f"{index + 1}:{item}\n{englishTranslations[index]}\n{aiTrans['output'][index]['es']}\n{zhCnTranslations[index]}\n{aiTrans['output'][index]['zh-tw']}\n\n"
        print(aiResult)
        postFeishu('\n'.join([f"{i + 1}. {word}" for i, word in enumerate(needTranslations)]), aiResult)


if __name__ == '__main__':
    print("上传简体中文")
    upload("./app/src/main/res/values-zh-rCN/strings.xml", "zh_CN")
    print("上传英文")
    upload("./app/src/main/res/values/strings.xml", "en")
    time.sleep(5.0)
    print("展示所有未翻译的单词")
    checkUnTranslate()
